import json

from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from relation.operating_sql import SQLManager

sql = SQLManager()

table = ''


def index(request):
    table_name = request.GET.get('tablename')
    if not table_name:
        status = "请勿空表查询"
        return render(request, "index.html", locals())
    with open("relation/static/config.txt", "r") as f:
        limit_dict = json.loads(f.read())
    print(limit_dict.keys())
    if table_name not in limit_dict.keys():
        limit_dict[table_name] = 0
        with open("relation/static/config.txt", "w") as f:
            f.write(str(limit_dict).replace("'", '"'))
        limit = 0
    else:
        limit = limit_dict[table_name]
    print(table_name)
    cx_sql = 'select * from %s where (A,B) not in (select cword,pword from word_relations_details) limit %d,5' % (
        table_name, limit)
    try:
        words_list = sql.get_dict_more(cx_sql)
        tablename = table_name
        status = "查询成功"
        return render(request, "index.html", locals())
    except:
        status = "查询失败，没有找到表名称"
        return render(request, "index.html", locals())


def relations(request, word,relations):
    A = word.split("__")[0]
    B = word.split("__")[1]
    tablename = word.split("__")[2]
    ins_sql = 'insert into word_relations_details(cword,pword,relations) values ("%s","%s","%s")' % (A, B, relations)
    sql.run(ins_sql)
    return redirect("/index/?tablename=" + tablename, locals())


def continueword(request, tablename):
    with open("relation/static/config.txt", "r") as f:
        limit_dict = json.loads(f.read())
    with open("relation/static/config.txt", "w+") as f:
        limit_dict[tablename] = limit_dict[tablename] + 1
        f.write(str(limit_dict).replace("'", '"'))
    return redirect("/index/?tablename=" + tablename, locals())
